package com.seeyon.apps.taxFund.manager.impl;

import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.commonExt.domain.Cap4Where;
import com.seeyon.apps.commonExt.util.CAP4FormDataManagerExt;
import com.seeyon.apps.commonExt.util.CommonRestUtil;
import com.seeyon.apps.commonExt.util.SaveToFlowUtilExt;
import com.seeyon.apps.commonExt.util.SaveToUnFlowUtilExt;
import com.seeyon.apps.taxFund.api.ShuiJinEnum;
import com.seeyon.apps.taxFund.api.domain.ProductQueryRes;
import com.seeyon.apps.taxFund.manager.GKInvoiceManager;
import com.seeyon.apps.util.CAP4FormKit;
import com.seeyon.apps.util.CommonUtilExt;
import com.seeyon.apps.util.EnumUtilExt;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.UUIDLong;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.util.*;


public class GKInvoiceManagerImpl implements GKInvoiceManager {

    private final AttachmentManager attachmentManager;

    private final FileManager fileManager;

    private final CAP4FormManager cap4FormManager;

    private final ColManager colManager;

    public GKInvoiceManagerImpl(AttachmentManager attachmentManager, FileManager fileManager, CAP4FormManager cap4FormManager, ColManager colManager) {
        this.attachmentManager = attachmentManager;
        this.fileManager = fileManager;
        this.cap4FormManager = cap4FormManager;
        this.colManager = colManager;
    }


    @Override
    public void receiveInvoice(List<Map<String, Object>> params) throws BusinessException, SQLException, IOException {
        for (Map<String, Object> param : params) {
            String xsdjbh = MapUtil.getStr(param, "xsdjbh");
            Assert.notBlank(xsdjbh, "单据编号不能为空");

            List<Map<String, Object>> invoices = MapUtil.get(param, "invoices", new TypeReference<List<Map<String, Object>>>() {
            }, null);
            if (CollectionUtil.isEmpty(invoices)) {
                return;
            }

            FormBean formBean = cap4FormManager.getFormByFormCode("fpkjsqdBillDsi");
            FormFieldBean billCodeFieldBean = CAP4FormKit.getFieldBean(formBean, "单据编号");
            Cap4Where where = new Cap4Where().eq(billCodeFieldBean.getName(), xsdjbh);
            List<FormDataMasterBean> formDataMasterBeans = CAP4FormDataManagerExt.selectMasterDataList(new FlipInfo(1, 1), formBean, null, where);
            Assert.notEmpty(formDataMasterBeans, "未找到单据编号【{}】的数据：", xsdjbh);
            Assert.isTrue(formDataMasterBeans.size() == 1, "单据编号【{}】找到多条", xsdjbh);
            FormDataMasterBean formDataMasterBean = formDataMasterBeans.get(0);

            Map<String, Object> formParams = new HashMap<>();
            List<Map<String, Object>> dtlList = new ArrayList<>();
            for (Map<String, Object> invoice : invoices) {
                String fphm = MapUtil.getStr(invoice, "fphm");
                String fpzl = MapUtil.getStr(invoice, "fpzl");
                String kprq = MapUtil.getStr(invoice, "kprq");
                String pdfUrl = MapUtil.getStr(invoice, "pdfUrl");
                Map<String, Object> dtlParams = new HashMap<>();
                dtlParams.put("发票号码", fphm);
                dtlParams.put("发票回写明细_发票类型", fpzl);
                dtlParams.put("发票回写明细_开票日期", kprq);

                if (StrUtil.isNotBlank(pdfUrl)) {
                    URL url = new URL(pdfUrl);
                    URLConnection connection = url.openConnection();
                    connection.setRequestProperty("User-Agent", "Mozilla/5.0");
                    try (InputStream inputStream = connection.getInputStream()) {
                        String fileName = "fapiao_" + System.currentTimeMillis() + "_" + (new Random()).nextInt(1000) + ".pdf";
                        V3XFile v3XFile = fileManager.save(inputStream, ApplicationCategoryEnum.cap4Form, fileName, new Date(), true);
                        Long fieldId = v3XFile.getId();
                        Long subRe = UUIDLong.longUUID();
                        ColManager colManager = (ColManager) AppContext.getBean("colManager");
                        ColSummary colSummary = colManager.getColSummaryByFormRecordId(formDataMasterBean.getId());
                        attachmentManager.create(new Long[]{fieldId}, ApplicationCategoryEnum.cap4Form, colSummary.getId(), subRe);
                        dtlParams.put("发票回写明细_附件", subRe);
                    }
                }
                if (MapUtil.isEmpty(dtlParams)) {
                    continue;
                }
                dtlList.add(dtlParams);
            }

            if (CollectionUtil.isEmpty(dtlList)) {
                continue;
            }
            formParams.put("明细_发票回写", dtlList);
            formParams.put("clearDtl", CommonUtilExt.list("明细_发票回写"));
            SaveToFlowUtilExt.saveOrUpdateFormData(formDataMasterBean, formParams);
        }
    }

    @Override
    public void productSync() throws BusinessException {
        String senderMember = AppContext.getSystemProperty("shuijin.rest.member");
        Assert.notBlank(senderMember, "请配置插件参数【{}】,", "shuijin.rest.member");
        String billDsi = AppContext.getSystemProperty("shuijin.billCodeDsi.productInfo");
        Assert.notBlank(billDsi, "请配置插件参数【{}】", "shuijin.billCodeDsi.productInfo");

        FormBean formBean = cap4FormManager.getFormByFormCode(billDsi);
        Assert.notNull(formBean, "表单【{}】不存在", billDsi);
        CAP4FormDataManagerExt.truncate(formBean.getMasterTableBean());;
        Map<String, Object> apiParams = new HashMap<>();
        boolean end = false;
        int pageNo = 1;
        while (!end) {
            apiParams.put("pageNo", pageNo);
            apiParams.put("pageSize", 500);
            ResponseEntity<String> post = CommonRestUtil.post(ShuiJinEnum.PRODUCT_QUERY, null, apiParams);
            String body = post.getBody();
            ProductQueryRes res = com.seeyon.ctp.util.json.JSONUtil.parseJSONString(body, ProductQueryRes.class);
            List<ProductQueryRes.DataInfo> data = res.getData();
            if (CollectionUtil.isEmpty(data)) {
                end = true;
                continue;
            }
            for (ProductQueryRes.DataInfo row : data) {
                Map<String, Object> formParams = new HashMap<>();
                formParams.put("商品大类", row.getSpdl());
                formParams.put("商品名称", row.getXmmc());
                formParams.put("纳税人识别号", row.getNsrsbh());
                formParams.put("税收分类编码", row.getSsflbm());
                formParams.put("税收分类简称", row.getSsfljc());
                formParams.put("规格型号", row.getGgxh());
                formParams.put("计量单位", row.getJldw());
                formParams.put("销售单价", row.getXsdj());
                formParams.put("税率_征收率", row.getSlv());
                if (StrUtil.isNotBlank(row.getYhzcbs())) {
                    CtpEnumItem ctpEnumItem = EnumUtilExt.getEnumItemByFormBeanAndFieldDisplayAndEnumItemVal(formBean, "优惠政策标识", row.getYhzcbs());
                    if (null != ctpEnumItem) {
                        formParams.put("优惠政策标识",  ctpEnumItem.getId());
                    }
                }
//                formParams.put("优惠政策标识文本", StrUtil.isNotBlank(row.getYhzcbs()) ? (StrUtil.equals(row.getYhzcbs(), "0") ? "不享受" : "享受") : "");
                String zzstsgl = row.getZzstsgl();
                formParams.put("增值税特殊管理", zzstsgl);
                String zzstsglwb;
                switch (zzstsgl) {
                    case "01":
                        zzstsglwb = "简易征收";
                        break;
                    case "02":
                        zzstsglwb = "稀土产品";
                        break;
                    case "03":
                        zzstsglwb = "免税";
                        break;
                    case "04":
                        zzstsglwb = "不征税";
                        break;
                    case "05":
                        zzstsglwb = "先征后退";
                        break;
                    case "06":
                        zzstsglwb = "100%先征后退";
                        break;
                    case "07":
                        zzstsglwb = "50%先征后退";
                        break;
                    case "08":
                        zzstsglwb = "按 3%简易征收";
                        break;
                    case "09":
                        zzstsglwb = "按 5%简易征收";
                        break;
                    case "10":
                        zzstsglwb = "按 5%简易征收减按 1.5%计征";
                        break;
                    case "11":
                        zzstsglwb = "即征即退 30%";
                        break;
                    case "12":
                        zzstsglwb = "即征即退 50%";
                        break;
                    case "13":
                        zzstsglwb = "即征即退 70%";
                        break;
                    case "14":
                        zzstsglwb = "即征即退 100%";
                        break;
                    case "15":
                        zzstsglwb = "超税负 3%即征即退";
                        break;
                    case "16":
                        zzstsglwb = "超税负 8%即征即退";
                        break;
                    case "17":
                        zzstsglwb = "超税负 12%即征即退";
                        break;
                    case "18":
                        zzstsglwb = "超税负 6%即征即退";
                        break;
                    default:
                        zzstsglwb = "";
                        break;
                }

                formParams.put("增值税特殊管理文本", zzstsglwb);
                formParams.put("会计科目", row.getDef01());
                SaveToUnFlowUtilExt.saveOrUpdateFormDataWithValid(senderMember, billDsi, null, formParams);
                pageNo++;
            }
        }

    }
}
